<script setup>
import { reactive, ref } from "vue";
import { communityListApi, carUseStatus, useAllCommunityList } from '@/hooks'
import { getUsageInfo, addUsageApi, editUsageApi, getUsageApi } from '@/api/usage.js'
import { ElMessage } from 'element-plus'

const getCommunityList = useAllCommunityList()
const emit = defineEmits(['updateList'])

const community = communityListApi()
const car = ref([])
//使用性质(租 售)
const carStatus = carUseStatus()
// console.log(carStatus);

// 表单ref引用
const formRef = ref()
// 弹窗控制变量
let isShow = ref(false);

const defaultState = {
    begin_time: '', //创建时间
    community_code: "", //小区名称
    cost: "", //总费用
    end_time: '', //结束时间
    license_plate: '', //车辆牌照
    owner: '', //车主姓名
    pk_code: '', //
    remark: '', //备注
    tel: '',
    type: '', //使用性质
    id: null,
    pk_code: '',
    name: ''
}
const formData = reactive({ ...defaultState })

//验证规则

var carPhoneValid = (rule, value, callback) => {
    const plateNumber = /^([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}(([0-9]{5}[DF])|([DF]([A-HJ-NP-Z0-9])[0-9]{4})))|([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳]{1})$/
    if (plateNumber.test(value)) {
        callback()
    } else {
        callback(new Error('请输入正确的车牌号'))
    }
}

const formRule = {
    community_code: [{ required: true, message: '所属小区编号不可为空且检查类型', trigger: 'blur' }],
    pk_code: [{ required: true, message: '请输入', trigger: 'blur' }],
    license_plate: [
        { required: true, message: '请输入', trigger: 'blur' },
        { validator: carPhoneValid, trigger: 'blur' }
    ],
    owner: [{ required: true, message: '请输入', trigger: 'blur' }],
    tel: [{ required: true, message: '请输入', trigger: 'blur' }],
    type: [{ required: true, message: '请选择', trigger: 'change' }],
    cost: [{ required: true, message: '请输入', trigger: 'blur' }],
    begin_time: [{ required: true, message: '请选择', trigger: 'blur' }],
    end_time: [{ required: true, message: '请选择', trigger: 'blur' }],
}

//标题优化（修改和新增）
const title = computed(() => {
    return formData.id ? '修改' : '新增'
})

//关闭事件
const closeHandler = () => {
    //移除校验
    formRef.value.resetFields()
    //重置表单数据
    Object.assign(formData, { ...defaultState })

}

// 表单提交
const onSubmit = async () => {
    try {
        //数据校验
        await formRef.value.validate()
        //2.整理数据 
        //3.提交数据
        formData.begin_time = +new Date(formData.begin_time)
        formData.end_time = +new Date(formData.end_time)
        const data = toRaw(formData)
        const res = formData.id ? await editUsageApi(data) : await addUsageApi(data)

        if (!res.success) {
            ElMessage.error(res.msg)
            isShow.value = false
            return
        }
        // console.log(res);

        //提示成功
        ElMessage.success('操作成功')

        //关闭
        isShow.value = false
        //跟新列表
        emit('updateList')
    } catch (error) {
        console.log(error);
    }
}

//数据回显
const replyData = async (id) => {
    let res = await getUsageInfo(id)
    console.log(res);
    isShow.value = true
    Object.assign(formData, res.data)
}
//级联
const usageList = ref([])
const changeHome = async (val) => {
    console.log(val);
    const res = await getUsageApi(val)
    usageList.value = res.data
    console.log(res.data);
    console.log(usageList.value, 111111);
}

defineExpose({
    isShow, replyData
})
</script>
<template>
    <el-drawer ref="formRef" v-model="isShow" :title="title" direction="rtl" size="50%" @close="closeHandler">
        <el-form ref="formRef" :model="formData" label-position="top" :rules="formRule">
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="所属小区" prop="community_code" :label-width="formLabelWidth">
                        <el-select @change="changeHome" slot="prepend" placeholder="请输入" size="large"
                            v-model="formData.community_code">
                            <el-option v-for="item in community" :key="item.id" :label="item.name" :value="item.code" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="车位名称" prop="name" :label-width="formLabelWidth">
                        <el-select slot="prepend" placeholder="请输入" size="large" v-model="formData.pk_code">
                            <el-option v-for="item in usageList" :key="item.id" :label="item.name" :value="item.code" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="车辆牌照" prop="license_plate">
                        <el-input placeholder="请输入" size="large" v-model="formData.license_plate" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="车主姓名" prop="owner">
                        <el-input placeholder="请输入" size="large" v-model="formData.owner" />
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="联系方式" prop="tel">
                        <el-input placeholder="请输入" size="large" v-model="formData.tel" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="使用性质" prop="type">
                        <el-radio-group v-model="formData.type">
                            <el-radio size="large" v-for="item in carStatus" :key="item.value" :label="item.value">
                                {{ item.label }}
                            </el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="总费用" prop="cost">
                        <el-input placeholder="请输入" size="large" v-model="formData.cost" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="备注" prop="remark">
                        <el-input placeholder="请输入" size="large" v-model="formData.remark" />
                    </el-form-item>
                </el-col>
            </el-row>



            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="开始时间" prop="begin_time">
                        <el-date-picker v-model="formData.begin_time" type="datetime" placeholder="选择日期时间" size="large" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="结束时间" prop="end_time">
                        <el-date-picker v-model="formData.end_time" type="datetime" placeholder="选择日期时间" size="large" />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <div>
            <el-button @click="isShow = false">取消</el-button>
            <el-button type="primary" @click="onSubmit">
                确定
            </el-button>
        </div>
    </el-drawer>
</template>

<style lang="scss" scoped></style>